import clone from 'lodash.clonedeep'
import moment from 'moment'
import Vue from 'vue'
import { handleDate } from '@/utils/excelDateUtil'
import { getConfig } from '@/api/process'
import store from '@/store'
//全局方法
export default {
  $checkRequireItem() {
    setTimeout(() => {
      const requireDom = document.querySelectorAll('.ant-form-item-required')
      const requireDomArray = Array.from(requireDom)
      requireDomArray.forEach((item) => {
        // let res = item.parentNode.nextSibling.children[0].children[0].classList.has('requiredFormItem')
        // console.log(res)
        // if (!res){
        item.parentNode.nextSibling.children[0].children[0].classList.add('requiredFormItem')
        // }
      })
    }, 0)
  },
  $assign(one, two) {
    if (two) {
      return { ...one, ...two }
      //后端尽返回些null
      // Object.keys(res).map(v => {
      //   if (!res[v]) {
      //     res[v] = one[v]
      //   }
      // })
      // return res
    }
    return { ...one }
  },
  $isEmpty(v) {
    if (v === undefined) {
      return true
    }
    if (v === null) {
      return true
    }
    if (v === '') {
      return true
    }
    return false
  },
  $console(v) {
    console.log(JSON.stringify(v, null, 4))
  },
  $clone(v) {
    if (v === undefined || v === null) return {}
    return clone(v)
  },
  $noticeSuccess(msg) {
    this.$message.success(msg)
  },
  $noticeWarning(msg) {
    this.$message.warning(msg)
  },
  $noticeError(msg) {
    this.$message.error(msg)
  },
  $isMe(rowId) {
    return this.$userInfo().id === rowId
  },

  // 解析url
  $parseURL(url) {
    const a = document.createElement('a')
    a.href = url
    return {
      host: a.hostname,
      port: a.port,
      query: a.search,
      params: (function () {
        const ret = {}
        const seg = a.search.replace(/^\?/, '').split('&')
        const len = seg.length
        let i = 0
        let s
        for (; i < len; i++) {
          if (!seg[i]) {
            continue
          }
          s = seg[i].split('=')
          ret[s[0]] = s[1]
        }
        return ret
      }()),
      hash: a.hash.replace('#', '')
    }
  },
  $dateFormat(val, type) {
    if (!val) return
    if (typeof val === 'string' && (val.length === 10 || val.length === 13)) {
      val = Number(val)
    }
    switch (type) {
      case 'Y':
        return moment(val).format('YYYY')
      case 'M':
        return moment(val).format('YYYY-MM')
      case 'M_CN':
        return moment(val).format('YYYY年MM月')
      case 'Q':
        return moment(val).format('YYYY年第Q季度')
      case 'D':
        return moment(val).format('YYYY-MM-DD')
      case 'm':
        return moment(val).format('YYYY-MM-DD HH:mm')
      case 'S':
        return moment(val).format('YYYY-MM-DD HH:mm:ss')
      default:
        return moment(val).format('YYYY-MM-DD HH:mm:ss')
    }
  },
  //上面那个res就是后端返回的所有值了，不需要在res.data了
  //cancelCb主要用于取消loading
  delList2(request, callback, params, cancelCb, message) {
    let that = this
    if (params.ids.length) {
      this.$confirm({
        title: '确定是否删除数据？',
        okText: '是',
        okType: 'danger',
        cancelText: '否',
        onOk() {
          request(params).then(res => {
            let msg = message || '删除成功'
            if (res.code === 200) {
              if (callback) {
                callback()
              }
              that.$message.success(msg)
            }
            cancelCb && cancelCb()
          })
        },
        onCancel() {
          cancelCb && cancelCb()
        }
      })
    } else {
      this.$message.warning('请选择要删除的数据')
    }
  },
  async $delList2(request, callback, params, cancelCb, message, title = '确定是否删除数据？') {
    if (params.ids.length) {
      this.$confirm({
        title,
        okText: '是',
        okType: 'danger',
        cancelText: '否',
        onOk: async () => {
          let res = await request(params)
          let msg = message || '删除成功'
          console.log(res)
          if (res.code === 200) {
            callback && await callback()
            this.$noticeSuccess(msg)
          }
          cancelCb && await cancelCb()
        },
        onCancel: async () => {
          cancelCb && await cancelCb()
        }
      })
    } else {
      this.$message.warning('请选择要删除的数据')
    }
  },
  async $delList3(request, callback, params, cancelCb, useMessage) {
    if (params) {
      this.$confirm({
        title: '确定是否删除数据？',
        okText: '是',
        okType: 'danger',
        cancelText: '否',
        onOk: async () => {
          let res = await request(params)
          let msg = '删除成功'
          if (useMessage) {
            msg = res.message
          }
          if (res.code === 200 || (res.data && res.data.code === 200) || res.code == '0') {
            console.log(res)
            callback && await callback(res)
            this.$noticeSuccess(msg)
          }
        },
        onCancel: async () => {
          cancelCb && await cancelCb()
        }
      })
    } else {
      this.$message.warning('请选择要删除的数据')
    }
  },
  async $delListHiden(request, callback, params, cancelCb, useMessage) {
    if (params) {
      this.$confirm({
        title: '确定是否删除数据？',
        okText: '是',
        okType: 'danger',
        cancelText: '否',
        onOk: async () => {
          let msg = '删除成功'
          request(params).then((res) => {
            if (useMessage) {
              msg = res.message
            }
            if (res.code === 200 || (res.data && res.data.code === 200)) {
              callback && callback(res)
              this.$noticeSuccess(msg)
            }
          }).catch((err) => {
          })
        },
        onCancel: async () => {
          cancelCb && await cancelCb()
        }
      })
    } else {
      this.$message.warning('请选择要删除的数据')
    }
  },
  $close() {
    if (location.pathname.search('process') !== -1) {
      window.close()
    } else {
      this.$multiTab.close()
    }
  },
  $closePage(e) {
    this.$multiTab.closePage(e)
  },
  $submitConfirm(cb, title = '请确认是否要提交，提交后不可修改') {
    this.$confirm({
      title,
      onOk: async () => {
        await cb()
      }
    })
  },
  $userInfo() {
    return JSON.parse(sessionStorage.getItem('ycloud-user_info'))
  },
  $currentPost() {
    if (this.$userInfo().currentPost.id) {
      return this.$userInfo().currentPost
    }
    return { code: '', id: '', name: '' }
  },
  //获取当前分公司
  $currentSubCompany() {
    let post = this.$currentPost()
    return { ...post, companyName: post.orgName, companyId: post.orgId }
  },
  $userType() {
    if (this.$userInfo()?.currentPost?.code) {
      return this.$userInfo().currentPost.code
    }
    return null
  },
  $fileUrl(file) {
    if (!file) return ''
    let token = Vue.getAcloudProvider().getAccessToken()
    return `/api/ycloud-file-center/oper/download?access_token=${token}&fileId=${file.fileId}`
  },
  $fileUrl2(file,flag) {
     if(flag){
      file = file[0]
     }
    if (!file) return ''
    let token = Vue.getAcloudProvider().getAccessToken()
    return `/api/ycloud-file-center/oper/download?access_token=${token}&fileId=${file.fileId}&fullfilename=${file.alias}`
  },
  $storageSet(key, value) {
    sessionStorage.setItem(key, JSON.stringify(value))
  },
  $storageGet(key, defaultValue = '') {
    let res = sessionStorage.getItem(key)
    if (res) {
      return JSON.parse(res)
    }
    return defaultValue
  },
  $storageClear(key, isAll = false) {
    if (isAll) {
      sessionStorage.clear()
    } else {
      sessionStorage.removeItem(key)
    }
  },
  $nav(path, query = {}) {
    this.$router.push({ path, query })
  },
  $formatDate(date, fmt) {
    return handleDate(date, fmt)
  },
  async $checkValidate(form) {
    return new Promise(resolve => {
      form.validate((valid) => {
        resolve(valid)
      })
    })
  },
  $btnPermission(value) {
    const authCode = ['prma_seex', 'prma_buco', 'prma_buqu']
    const authPrefix = ['seex_', 'buco_', 'buqu_']
    const btnPermissionList = store.getters.btnPermission
    const activeCodes = store.state.user.activeCodes[1];
    if (authCode.includes(activeCodes)) {
      const idx = authCode.findIndex(item => item === activeCodes)
      if (idx > -1 && idx !== 2) {
        value = authPrefix[idx] + value
      } else {
        return true
      }
      const index = btnPermissionList.findIndex(item => item.code === value)
      if (index > -1) {
        return true
      }
      return false
    }
    return true
  },
  $getConfigFn(data) {
    //sumbitAssignVal 提交审批人的值，urge是否加急
    //dataSum 1指定审批人设置-是,2指定审批人设置-是 加急,3指定审批人设置-否；加急,4指定审批人设置-否；不加急
    var sumbitAssignVal = null, urge = null, dataSum = null;
    return getConfig({ processKey: data }).then((res) => {
      if (res.code === 200) {
        let data = res.data;
        data.length && data.map((item) => {
          if (item.keyCol === 'SUMBIT_ASSIGN') {
            sumbitAssignVal = item.keyValue;
          } else if (item.keyCol === 'URGE') {
            urge = item.keyValue;
          }
        })
        if (sumbitAssignVal * 1 === 0 && urge * 1 === 0) {
          dataSum = 4
        } else if (sumbitAssignVal * 1 === 0 && urge * 1 === 1) {
          dataSum = 3
        }
        else if (sumbitAssignVal * 1 === 1 && urge * 1 === 1) {
          dataSum = 2
        } else {
          dataSum = 1
        }
      }
      return dataSum
    })
  },


}
